package top.icecola.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import top.icecola.community.domain.DiscussPost;
import top.icecola.community.domain.Page;
import top.icecola.community.domain.User;
import top.icecola.community.service.DiscussPostService;
import top.icecola.community.service.LikeService;
import top.icecola.community.service.UserService;
import top.icecola.community.util.CommunityConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController implements CommunityConstant {
    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/home")
    public String pageDiscussPosts(Model model, Page page){
        page.setRows(discussPostService.findDiscussPostRows());
        page.setPath("/home");
        page.setLimit(5);
//        System.out.println(page.getRows());
        List<DiscussPost> list = discussPostService.pageDiscussPosts(page.getCurrent(), page.getLimit());
//        System.out.println(list);
        List<Map<String,Object>> discussPosts=new ArrayList<>();
        if(list!=null){
            for(DiscussPost post:list){
                Map<String,Object>map=new HashMap<>();
                map.put("post",post);
                User user=userService.findUserById(post.getUserId());
                map.put("user",user);

                long entityLikeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,post.getId());
                map.put("likeCount",entityLikeCount);
                discussPosts.add(map);
            }
        }
//        System.out.println(discussPosts.size());
        model.addAttribute("discussPosts",discussPosts);
        return "/site/home";
    }

    @GetMapping("/denied")
    public  String getDeniedPage(){
        return "/error/404";
    }

    @GetMapping("/index")
    public String getHome(){
        return "/index";
    }
}
